チュートリアル 2
◆インタラクションの 10 ステップ
Step 11. マウスカーソルの座標
Cursor::Pos() は現在のカーソルの座標を返します
座標は Point 型で、整数の値 x と y を持ちます
code:cpp
# include <Siv3D.hpp>
void Main()
{
while (System::Update())
{
ClearPrint();
Point pos = Cursor::Pos();
int32 x = Cursor::Pos().x;
int32 y = pos.y;
Print << pos;
Print << x;
Print << y;
}
}
Step 12. マウスのクリック
MouseL.down() はマウスの左ボタンがクリックされたかを返します
if ( ) の中に入れれば、クリックしたときのプログラムを書けます
code:cpp
# include <Siv3D.hpp>
void Main()
{
while (System::Update())
{
if (MouseL.down())
{
Print << U"down";
}
}
}
Step 13. マウスのボタンが離された
MouseL.up() はマウスの左ボタンが離されたかを返します
code:cpp
# include <Siv3D.hpp>
void Main()
{
while (System::Update())
{
if (MouseL.up())
{
Print << U"up";
}
}
}
Step 14. マウスがおされている
MouseL.pressed() はマウスの左ボタンが押されているかを返します
code:cpp
# include <Siv3D.hpp>
void Main()
{
int32 x = 0;
while (System::Update())
{
ClearPrint();
if (MouseL.pressed())
{
++x;
}
Print << x;
}
}
Step 15. キー入力
MouseL の代わりに KeyA や KeySpace, KeyEnter などでキーの入力を判定できます
code:cpp
# include <Siv3D.hpp>
void Main()
{
while (System::Update())
{
if (KeyA.down())
{
Print << U"A";
}
if (KeySpace.down())
{
Print << U"Space";
}
if (KeyEnter.down())
{
Print << U"Enter";
}
}
}
Step 16. クリックした場所に移動
Point 型の変数を用意して、クリックすると円がそこに移動するようにします
code:cpp
# include <Siv3D.hpp>
void Main()
{
Point pos(320, 240);
while (System::Update())
{
if (MouseL.down())
{
pos = Cursor::Pos();
}
Circle(pos, 30).draw();
}
}
Step 17. キーで移動
Point 型の変数の成分 x, y を矢印キーで操作できるようにします
code:cpp
# include <Siv3D.hpp>
void Main()
{
Point pos(320, 240);
while (System::Update())
{
if (KeyLeft.down())
{
pos.x -= 2;
}
if (KeyRight.down())
{
pos.x += 2;
}
if (KeyUp.down())
{
pos.y -= 2;
}
if (KeyDown.down())
{
pos.y += 2;
}
Circle(pos, 30).draw();
}
}
Step 18. 図形のマウスオーバー
図形の変数を作って、mouseOver()すると、その図形上にマウスカーソルがあるかどうかを判定できます
code:cpp
# include <Siv3D.hpp>
void Main()
{
const Rect rect(40, 40, 200, 80);
while (System::Update())
{
if (rect.mouseOver())
{
rect.draw(Palette::Red);
}
else
{
rect.draw(Palette::Yellow);
}
}
}
C++ の条件演算子 ? :を使うともっと短く書けます
code:cpp
# include <Siv3D.hpp>
void Main()
{
const Rect rect(40, 40, 200, 80);
while (System::Update())
{
rect.draw(rect.mouseOver() ? Palette::Red : Palette::Yellow);
}
}
Step 19. 図形のクリック
図形の変数を作って、leftClicked()すると、その図形が左クリックされたかを判定できます
leftPressed() や leftReleased() もあります
code:cpp
# include <Siv3D.hpp>
void Main()
{
const Rect rect(40, 40, 200, 80);
int32 count = 0;
while (System::Update())
{
ClearPrint();
rect.draw(rect.mouseOver() ? Palette::Red : Palette::Yellow);
if (rect.leftClicked())
{
++count;
}
Print << count;
}
}
Step 20. 情報の蓄積
Array<型> の変数は <<で情報を蓄積できます(動的配列)
for (const auto& value : 配列) ループで、個々の要素に value を通してアクセスできます
code:cpp
# include <Siv3D.hpp>
void Main()
{
Array<Circle> circles;
while (System::Update())
{
if (MouseL.down())
{
circles << Circle(Cursor::Pos(), 20);
}
for (const auto& circle : circles)
{
circle.draw();
}
}
}